package cn.itsource.user.controller;

import cn.itsource.user.domain.LoginInfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.domain.dto.UserDto;
import cn.itsource.user.service.IUserService;
import cn.itsource.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/register")
    public AjaxResult register(@RequestBody UserDto userDto){
        try {
            userService.register(userDto);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
    }



    @PostMapping("/login")
    public AjaxResult login(@RequestBody User user){
        try {
            LoginInfo loginInfo = userService.login(user);
            String token = UUID.randomUUID().toString();
            //把当前的登录用户放到session里面
            redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);

            Map<String,Object>map =new HashMap<>();
            //携带token
            map.put("token",token);
            //清空敏感数据
            loginInfo.setPassword("");
            loginInfo.setSalt("");
            map.put("loginInfo",loginInfo);
            return AjaxResult.me().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
    }

}
